package com.usian.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.search.dtos.UserSearchDto;
import com.usian.search.service.SearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.repository.query.ReactiveStringBasedMongoQuery;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public ResponseResult search(UserSearchDto dto) {

        if(dto==null || dto.getMinBehotTime()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        List<Map> articleList =new ArrayList<>();
        try {

            /**
             * restHighLevelClient.search
             *    SearchRequest source()
             *       SearchSourceBuilder  query()
             *          BoolQueryBuilder
             *          QueryStringQueryBuilder
             *          RangeQueryBuilder
             *       SearchSourceBuilder 分页 排序
             *
             *
             */
            SearchRequest searchRequest =new SearchRequest("app_info_article");
            SearchSourceBuilder searchSourceBuilder =new SearchSourceBuilder();

            BoolQueryBuilder boolQueryBuilder =QueryBuilders.boolQuery();

            QueryStringQueryBuilder builder = QueryBuilders.queryStringQuery(dto.getSearchWords())
                    .field("title").field("content").defaultOperator(Operator.OR);

            boolQueryBuilder.must(builder);

            RangeQueryBuilder queryBuilder=QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime());
            boolQueryBuilder.filter(queryBuilder);
            searchSourceBuilder.query(boolQueryBuilder);

            //分页
            searchSourceBuilder.from(dto.getPageNum());
            searchSourceBuilder.size(dto.getPageSize());

            //排序
            searchSourceBuilder.sort("publishTime", SortOrder.DESC);
            searchRequest.source(searchSourceBuilder);
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);



            SearchHit[] hits = searchResponse.getHits().getHits();
            for(SearchHit hit:hits){
                String sourceAsString = hit.getSourceAsString();  //es  json提交   json响应
                Map map = JSON.parseObject(sourceAsString, Map.class);
                articleList.add(map);
            }
        } catch (IOException e) {
            e.printStackTrace();
            ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

        return ResponseResult.okResult(articleList);
    }
}
